package cheme.ProcessEditor.Parts.Streams.Tag;

import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.editpolicies.ComponentEditPolicy;
import org.eclipse.gef.requests.GroupRequest;

import cheme.ProcessEditor.Parts.IFieldPart;
import cheme.ProcessEditor.Tools.CreateAfterRequest;
import cheme.ProcessModel.Cmds.DeleteCmd;
import cheme.ProcessModel.ProcessUnits.Streams.Tags.TagComponent;


public class PolicyTagComponent extends ComponentEditPolicy
{
	@Override
	public Command getCommand(Request request)
	{
		if(request instanceof CreateAfterRequest)
		{
//			 Give my parent a chance to create a new me after me.
//
//			 If the request originated with this policies host, no need to
//			 add it again.
			
			if(!((CreateAfterRequest)request).getAfterList().contains(getHost()))
			{
				((CreateAfterRequest)request).addToAfterList(getHost());
			}
			
			return getHost().getParent().getCommand(request);
		}
		
		return super.getCommand(request);
	}
	
	@Override
	protected Command getDeleteCommand(GroupRequest request)
	{		
		CompoundCommand gCmd = new CompoundCommand();
		
		for(Object o : request.getEditParts())
		{
			if((o instanceof PartTagComponent) || //delete request from me
				(o instanceof IFieldPart && getHost().getChildren().contains(o))) //request from a child
			{
//				TagComponentList descriptorList = (TagComponentList)getHost().getParent().getModel(); 
				TagComponent descriptor = (TagComponent)getHost().getModel();
				Command cmd = null;
				
//				/*
//				 * Are we deleting te last element in the list? If so, delete the
//				 * list too.
//				 */
//				if(1 == descriptorList.getChildren().size())
//				{
//					GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
//					deleteReq.setEditParts(getHost().getParent());
//										
//					cmd = getHost().getParent().getCommand(deleteReq);
//					
//					if(null != cmd)
//					{
//						gCmd.add(cmd);
//					}
//				}
//				else
				{
					/*
					 * A child field has forwarded a delete to me. I will delete
					 * myself.
					 */
	
					cmd = new DeleteCmd(descriptor);
					gCmd.add(cmd);
				}
			}
			else
			{
				throw new Error("A forwarded delete command should contain a single child.");
			}
		}
		
		return gCmd.unwrap();
	}	
}
